package com.iweb.user.servlet;

import com.iweb.user.model.User;
import com.iweb.user.service.UserService;
import com.iweb.user.service.UserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(value="*.User")
public class UserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String path = req.getServletPath();

        switch (path) {
            case "/login.User":
                login(req, resp);
                break;
            case "/logout.User":
                logout(req, resp);
                break;
            case "/addUser.User":
                addUser(req, resp);
                break;
            case "/viewUser.User":
                viewUser(req, resp);
                break;
            case "/deleteUser.User":
                deleteUser(req, resp);
                break;
            case "/updateUser.User":
                updateUser(req, resp);
                break;
            case "/queryFullName.User":
                queryFullName(req, resp);
                break;
            case"/checkedusername.User":
                checkedusername(req, resp);
                break;
            default:
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
    private void queryFullName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj != null) {
            User user = (User) userObj;
            String userfullname = user.getUserfullname();
            resp.getWriter().print(userfullname);
        } else {
            resp.getWriter().print("");
        }
    }

    // 用户登录
    private void login(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 密码加密
        if (password != null && !password.trim().equals("")) {
            password = DigestUtils.md5Hex(password);
        }

        // 验证用户登录
        boolean result = userService.isLogin(username, password, req.getSession());
        if (result) {
            resp.sendRedirect(req.getContextPath() + "/main.html");
        } else {
            resp.sendRedirect(req.getContextPath() + "/login.html?islogin=0");
        }
    }

    // 用户注册
    private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String userfullname = req.getParameter("userfullname");
        String password = req.getParameter("password");
        password = DigestUtils.md5Hex(password);
        String phone = req.getParameter("phone");

        User user = new User(null, username, userfullname, password, phone);
        userService.saveOne(user);
        resp.sendRedirect(req.getContextPath() + "/login.html?register=success");
    }

    // 查看用户信息
    // 查看用户信息
    private void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        User user = (User) req.getSession().getAttribute("user");

        // 检查用户是否已登录
        if (user == null) {
            resp.getWriter().print("{\"success\":false,\"message\":\"未登录\"}");
            return;
        }

        // 查询并返回用户信息
        User fullUser = userService.getUserById(user.getUserid());
        String res = "{\"success\":true,\"user\":{\"userid\":" + fullUser.getUserid() +
                ",\"username\":\"" + fullUser.getUsername() + "\"" +  // 添加缺失的引号
                ",\"userfullname\":\"" + fullUser.getUserfullname() + "\"" +  // 添加缺失的引号
                ",\"phone\":\"" + (fullUser.getPhone() != null ? fullUser.getPhone() : "") + "\"}}";
        resp.getWriter().print(res);

    }


    // 删除用户
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        User user = (User) req.getSession().getAttribute("user");

        if (user == null) {
            resp.getWriter().print("{\"success\":false,\"message\":\"未登录\"}");
            return;
        }

        boolean result = userService.deleteUser(user.getUserid());
        if (result) {
            req.getSession().removeAttribute("user");
            resp.getWriter().print("{\"success\":true,\"message\":\"用户删除成功\"}");
        } else {
            resp.getWriter().print("{\"success\":false,\"message\":\"用户删除失败\"}");
        }
    }

    // 更新用户信息
    private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        User sessionUser = (User) req.getSession().getAttribute("user");

        if (sessionUser == null) {
            resp.getWriter().print("{\"success\":false,\"message\":\"未登录\"}");
            return;
        }

        // 获取表单数据
        String userfullname = req.getParameter("userfullname");
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");

        // 创建用户对象
        User user = new User();
        user.setUserid(sessionUser.getUserid());
        user.setUsername(sessionUser.getUsername());
        user.setUserfullname(userfullname);
        user.setPhone(phone);

        // 处理密码更新
        if (password != null && !password.trim().equals("")) {
            password = DigestUtils.md5Hex(password);
            user.setPassword(password);
        } else {
            user.setPassword(sessionUser.getPassword());
        }

        // 更新用户信息
        boolean result = userService.updateUser(user);
        if (result) {
            // 更新session中的用户信息
            sessionUser.setUserfullname(userfullname);
            sessionUser.setPhone(phone);
            if (password != null && !password.trim().equals("")) {
                sessionUser.setPassword(password);
            }
            req.getSession().setAttribute("user", sessionUser);

            resp.getWriter().print("{\"success\":true,\"message\":\"用户信息更新成功\"}");
        } else {
            resp.getWriter().print("{\"success\":false,\"message\":\"用户信息更新失败\"}");
        }
    }

    // 用户退出
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("user");
        resp.sendRedirect(req.getContextPath() + "/login.html");
    }
    private void checkedusername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean flag = userService.isContainUserName(username);
        String res = "";
        if (flag) {
            res = "{\"flag\":1}";
        } else {
            res = "{\"flag\":0}";
        }
        resp.getWriter().print(res);
    }
}
